package MainPackage
{
  import flash.events.Event;
  import flash.events.EventDispatcher;
  import flash.events.IEventDispatcher;
  import flash.events.TimerEvent;
  import flash.utils.Timer;
  import MainPackage.events.RadioHistoryEvent;
  import mx.collections.ArrayList;
  import Tools.Debug;
  import Tools.HtmlSpecials;
  import vk.RemoteVars;

  /**
   * ...
   * @author Roman Marchenko
   */
  public class RadioHistory extends EventDispatcher
  {
    public static const MAX : uint = 10;

    private static const VAR_NAME : String = "radio_history";
    private var entries : Array;
    private var changed : Boolean;

    public function RadioHistory(target : IEventDispatcher = null)
    {
      super(target);
      changed = false;
      dispatchEvent(new Event("arrayChanged"));
    }

    CONFIG::debug
    public function clear() : void
    {
      entries = new Array;
      dispatchEvent(new Event("arrayChanged"));
    }

    [Bindable(event='arrayChanged')]
    public function get array() : ArrayList
    {
      return new ArrayList(entries);
    }

    [Bindable(event='loadingChanged')]
    public function get isLoading() : Boolean
    {
      return (null == entries);
    }

    public function load() : void
    {
      Debug.log("RadioHistory.load");
      var str : String = RemoteVars.getVar(RemoteVars.RADIO_HISTORY);
      str = HtmlSpecials.decode(str);
      var arr : Array = str.split(";");
      if (!entries)
      {
        entries = new Array;
      }
      entries = entries.concat(arr);
      entries = entries.filter(removedDuplicates);
      if (entries.length > MAX)
      {
        entries = entries.slice(0, MAX);
      }
      Debug.log("RadioHistory.onLoadOk: processed: " + entries);
      var event : RadioHistoryEvent = new RadioHistoryEvent(RadioHistoryEvent.READ_COMPLETE);
      dispatchEvent(event);
      dispatchEvent(new Event("arrayChanged"));
      dispatchEvent(new Event("loadingChanged"));
    }

    public function add(entry : String) : void
    {
      Debug.log("RadioHistory.add: " + entry);
      var i : int = entries.indexOf(entry);
      if (-1 == i)
      {
        entries.unshift(entry);
        if (entries.length > MAX)
        {
          entries = entries.slice(0, MAX);
        }
      }
      else
      {
        // Move the found entry to the beginning of the array.
        entries.splice(i, 1);
        entries.unshift(entry);
      }

      dispatchEvent(new Event("arrayChanged"));
      changed = true;
      put();
    }

    public function getAt(index : uint) : String
    {
      Debug.log("RadioHistory.getAt: " + index);
      return (index < entries.length ? entries[index] : null);
    }

    public function size() : uint
    {
      return (entries ? entries.length : 0);
    }

    private function removedDuplicates (item : Object, idx : uint, arr : Array) : Boolean
    {
      return arr.indexOf(item) == idx;
    }

    private function put() : void
    {
      Debug.log("RadioHistory.put: " + entries.join(";"));
      //var storage : RemoteVars = new RemoteVars;
      //storage.addEventListener(RemoteVarsEvent.OK_PUTVAR, onPutOk);
      //storage.addEventListener(RemoteVarsEvent.TOO_MANY_REQUESTS, onTooManyRequestsError);
      //storage.addEventListener(RemoteVarsEvent.ERROR, onPutError);
      RemoteVars.putVar(VAR_NAME, entries.join(";"), onPutOk, onPutError);

      changed = false;
    }

    private function onPutOk(key:String, value:String) : void
    {
      Debug.log("RadioHistory.onOk: " + key);
      if (value == entries.join(";"))
      {
        Debug.log("RadioHistory.onOk: write complete");
        var event : RadioHistoryEvent = new RadioHistoryEvent(RadioHistoryEvent.WRITE_COMPLETE);
        dispatchEvent(event);
      }
    }

    private function onPutError(e:String) : void
    {
      Debug.log("RadioHistory.onError: " + e);
      var event : RadioHistoryEvent = new RadioHistoryEvent(RadioHistoryEvent.WRITE_ERROR);
      dispatchEvent(event);
      changed = true;
    }

    private function onTooManyRequestsError(e : String) : void
    {
      Debug.log("RadioHistory.onTooManyRequestsError: restarting timer...");
      changed = true;
    }

    private function onGetError(e : String) : void
    {
      Debug.log("RadioHistory.onError: " + e);
      var event : RadioHistoryEvent = new RadioHistoryEvent(RadioHistoryEvent.READ_ERROR);
      dispatchEvent(event);
    }
  }

}